const ABILITY_TYPE_EXTERNAL = 0;
const ABILITY_TYPE_INTERNAL = 1;
const ACTION_SYNC = 0;
const ACTION_ASYNC = 1;

/**
 * 简化Java方法的调用
 */
export default class JavaObject {
    /**
     * 默认构造，需要绑定调用Java对象的包名和类名
     *
     * @param bundleName Java的包名
     * @param abilityName Java的Ability名
     * @param isInternal 调用的类型，true内部，false外部，分为外部(Ability)和内部(AceInternalAbility)
     * @param isSync 调用方式，true同步，false异步，分为同步和异步
     */
    constructor(bundleName, abilityName, isInternal, isSync) {
        if (!isSync && !isInternal) {
            console.error("当前异步方式仅支持AbilityType为Internal Ability类型")
        }
        this.bundleName = bundleName
        this.abilityName = abilityName
        this.abilityType = isInternal ? ABILITY_TYPE_INTERNAL : ABILITY_TYPE_EXTERNAL
        this.syncOption = isSync ? ACTION_SYNC : ACTION_ASYNC
    }

    /**
     * 简化调用FeatureAbility#callAbility，注意：当前异步方式仅支持AbilityType为Internal Ability类型
     * callAbility用于执行方法，单次数据交互
     *
     * @param functionCode  对应Java端的调用识别码，需与Java端协调一致
     * @param data 传递给Java端的数据
     */
    call(functionCode, data) {
        var action = {
            bundleName: this.bundleName,
            abilityName: this.abilityName,
            messageCode: functionCode,
            data: data,
            abilityType: this.abilityType,
            syncOption: this.syncOption
        }
        return FeatureAbility.callAbility(action);
    }

    /**
     * 简化调用FeatureAbility#subscribeAbilityEvent，注意：当前异步方式仅支持AbilityType为Internal Ability类型
     * subscribeAbilityEvent用于订阅方法，订阅后Java端的变化都会通知到Js端，持续数据交互，需要主动取消订阅
     *
     * @param functionCode  对应Java端的调用识别码，需与Java端协调一致
     * @param callback Java端方法执行的结果，返回给Js端订阅的callback
     */
    subscribe(functionCode, callback) {
        var action = {
            bundleName: this.bundleName,
            abilityName: this.abilityName,
            messageCode: functionCode,
            abilityType: this.abilityType,
            syncOption: this.syncOption
        }
        return FeatureAbility.subscribeAbilityEvent(action, (result) => {
            callback(result)
        });
    }

    /**
     * 简化调用FeatureAbility#unsubscribeAbilityEvent，注意：当前异步方式仅支持AbilityType为Internal Ability类型
     *
     * @param functionCode 对应Java端的调用识别码，需与Java端协调一致
     */
    unsubscribe(functionCode) {
        var action = {
            bundleName: this.bundleName,
            abilityName: this.abilityName,
            messageCode: functionCode,
            abilityType: this.abilityType,
            syncOption: this.syncOption
        }
        FeatureAbility.unsubscribeAbilityEvent(action)
    }
}

